package com.deli.talkbetter.llm;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MaaS {
    public static final String TAG = "MaaS";

    private List<GrammarQuestion> questions;
    private List<ReadingPassage> readingPassages;
    private int currentQuestionIndex = 0;
    private int question_count = 10;
    private int reading_count = 2;
    private int reading_question_count = 3;
    
    // 添加回调接口
    public interface QuestionsCallback {
        void onQuestionsLoaded(List<GrammarQuestion> questions);
        void onError(String error);
    }
    
    // 添加获取单词翻译的回调接口
    public interface TranslationCallback {
        void onTranslationLoaded(String translation);
        void onError(String error);
    }
    
    // 添加获取阅读理解的回调接口
    public interface ReadingPassagesCallback {
        void onReadingPassagesLoaded(List<ReadingPassage> passages);
        void onError(String error);
    }
    
    private QuestionsCallback questionsCallback;
    private ReadingPassagesCallback readingPassagesCallback;

    public MaaS(){

    }
    
    // 设置回调
    public void setQuestionsCallback(QuestionsCallback callback) {
        this.questionsCallback = callback;
    }
    
    // 设置阅读理解回调
    public void setReadingPassagesCallback(ReadingPassagesCallback callback) {
        this.readingPassagesCallback = callback;
    }

    public void fetchQuestionsFromAPI(Context ctx) {
        if (!isNetworkAvailable(ctx)) {
            Log.d(TAG, "fetchQuestionsFromAPI: 无网络");
            if (questionsCallback != null) {
                questionsCallback.onError("无网络连接");
            }
            return;
        }

        Log.d(TAG, "fetchQuestionsFromAPI: 开始网络请求......");

        // 配置OkHttpClient，增加超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();

        // 构造请求体
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("model", "DeepSeek-V3");
            jsonBody.put("temperature", 0.8);
            jsonBody.put("messages", new JSONArray()
                    .put(new JSONObject()
                            .put("role", "system")
                            .put("content", "You are a helpful assistant. You generate English grammar questions for middle school students. You must return ONLY valid JSON data without any markdown formatting, code blocks (no ```json or ```), or additional text. Just return the pure JSON array. Keep the response concise and respond quickly. Make sure to create diverse questions each time, covering various difficulty levels and grammar points."))
                    .put(new JSONObject()
                            .put("role", "user")
                            .put("content",
                                    "生成"+question_count+"道适合初中学生的英语语法选择题，全面覆盖以下语法知识点：时态（一般现在时、现在进行时、一般过去时、一般将来时、现在完成时）、语态、情态动词、非谓语动词、形容词和副词的比较级与最高级、冠词、介词、连词、名词的数与格、主谓一致、宾语从句、状语从句、定语从句等。每题包含4个选项，格式为 A.、B.、C.、D.。"+
                                            "请确保每次生成的题目都尽可能多样化，避免重复或相似的题目内容。"+
                                            "题目应该覆盖不同的难度等级，包括基础、中等和较高难度的题目。"+
                                            "每次生成的题目应该有不同的话题背景，比如体育、音乐、科技、旅游、学校生活、节日等。"+
                                            "请严格按照以下JSON数组格式直接返回，不要包含任何额外的文本、解释或代码块，只返回JSON数组本身。"+
                                            "每个题目对象必须包含以下字段："+
                                            "question（题目内容，字符串），"+
                                            "options（选项列表，包含4个字符串的数组，每个选项以 'A. '、'B. '、'C. '、'D. ' 开头），"+
                                            "correct_answer（正确选项的索引，从0开始的整数），"+
                                            "explanation（答案解析，字符串，说明正确选项的理由及错误选项的排除原因，语言简洁清晰，适合初中生理解）。"+
                                            "示例格式："+
                                            "[{"+
                                            "\"question\": \"Look! It ________ raining.\","+
                                            "\"options\": [\"A. is\", \"B. are\", \"C. was\", \"D. were\"],"+
                                            "\"correct_answer\": 0,"+
                                            "\"explanation\": \"句中 'Look!' 表明动作正在发生，应使用现在进行时。主语 'it' 为单数，be 动词用 is，因此正确答案是 A. is。\""+
                                            "}]"
                            )));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );

        // 注意：这里需要替换为实际的大模型API地址
        Request request = new Request.Builder()
                .url("https://api.modelarts-maas.com/v1/chat/completions")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer xxx") // 如果需要认证
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: 网络请求失败");
                e.printStackTrace();
                if (questionsCallback != null) {
                    questionsCallback.onError("网络请求失败");
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d(TAG, "onResponse: 网络请求成功");
                    try {
                        String responseData = response.body().string();
                        Log.d(TAG, "onResponse: 响应数据：" + responseData);

                        // 解析响应数据
                        JSONObject responseJson = new JSONObject(responseData);
                        JSONArray choices = responseJson.getJSONArray("choices");
                        JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                        String content = message.getString("content");

                        parseQuestionsFromResponse(content);
                        
                        // 通知回调
                        if (questionsCallback != null && questions != null) {
                            questionsCallback.onQuestionsLoaded(questions);
                        }
                    } catch (Exception e) {
                        Log.d(TAG, "onResponse: 网络请求异常");
                        e.printStackTrace();
                        if (questionsCallback != null) {
                            questionsCallback.onError("解析数据失败");
                        }
                    }
                } else {
                    Log.d(TAG, "onResponse: fail");
                    if (questionsCallback != null) {
                        questionsCallback.onError("请求失败");
                    }
                }
            }
        });
    }
    
    // 获取单词的中文翻译
    public void fetchWordTranslation(Context ctx, String word, TranslationCallback callback) {
        if (!isNetworkAvailable(ctx)) {
            Log.d(TAG, "fetchWordTranslation: 无网络");
            callback.onError("无网络连接");
            return;
        }

        Log.d(TAG, "fetchWordTranslation: 开始网络请求......");

        // 配置OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

        // 构造请求体
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("model", "DeepSeek-V3");
            jsonBody.put("temperature", 0.7);
            jsonBody.put("messages", new JSONArray()
                    .put(new JSONObject()
                            .put("role", "system")
                            .put("content", "You are a helpful assistant that translates English words to Chinese. Return ONLY the Chinese translation without any additional text or formatting."))
                    .put(new JSONObject()
                            .put("role", "user")
                            .put("content", "Translate the following English word to Chinese: " + word + ". Return ONLY the Chinese translation without any additional text or formatting.")));
        } catch (JSONException e) {
            e.printStackTrace();
            callback.onError("构建请求失败");
            return;
        }

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );

        Request request = new Request.Builder()
                .url("https://api.modelarts-maas.com/v1/chat/completions")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer xxx")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: 网络请求失败");
                e.printStackTrace();
                callback.onError("网络请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d(TAG, "onResponse: 网络请求成功");
                    try {
                        String responseData = response.body().string();
                        Log.d(TAG, "onResponse: 响应数据：" + responseData);

                        // 解析响应数据
                        JSONObject responseJson = new JSONObject(responseData);
                        JSONArray choices = responseJson.getJSONArray("choices");
                        JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                        String translation = message.getString("content");

                        // 通知回调
                        callback.onTranslationLoaded(translation.trim());
                    } catch (Exception e) {
                        Log.d(TAG, "onResponse: 网络请求异常");
                        e.printStackTrace();
                        callback.onError("解析数据失败");
                    }
                } else {
                    Log.d(TAG, "onResponse: fail");
                    callback.onError("请求失败");
                }
            }
        });
    }
    
    // 获取阅读理解内容
    public void fetchReadingPassagesFromAPI(Context ctx) {
        if (!isNetworkAvailable(ctx)) {
            Log.d(TAG, "fetchReadingPassagesFromAPI: 无网络");
            if (readingPassagesCallback != null) {
                readingPassagesCallback.onError("无网络连接");
            }
            return;
        }

        Log.d(TAG, "fetchReadingPassagesFromAPI: 开始网络请求......");

        // 配置OkHttpClient，增加超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();

        // 构造请求体
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("model", "DeepSeek-V3");
            jsonBody.put("temperature", 0.8);
            jsonBody.put("messages", new JSONArray()
                    .put(new JSONObject()
                            .put("role", "system")
                            .put("content", "You are a helpful assistant. You generate English reading comprehension passages for middle school students. You must return ONLY valid JSON data without any markdown formatting, code blocks (no ```json or ```), or additional text. Just return the pure JSON array. Keep the response concise and respond quickly."))
                    .put(new JSONObject()
                            .put("role", "user")
                            .put("content",
                                    "生成"+reading_count+"篇适合中国初中学生的英语阅读理解文章，每篇文章约500个单词，配有"+reading_question_count+"道选择题。文章和题目应符合初中生的英语水平，主题可以包括科技、文化、教育、生活、历史、寓言、军事等方面，文章要非常有趣，能够吸引学生阅读兴趣。" +
                                            "请严格按照以下JSON数组格式直接返回，不要包含任何额外的文本、解释或代码块，只返回JSON数组本身。" +
                                            "每个文章对象必须包含以下字段：" +
                                            "title（文章标题，字符串），" +
                                            "content（文章内容，字符串），" +
                                            "questions（问题数组，每个问题包含question、options、correct_answer和explanation字段）。" +
                                            "questions中的每个问题对象必须包含以下字段：" +
                                            "question（题目内容，字符串），" +
                                            "options（选项列表，包含4个字符串的数组，每个选项以 'A. '、'B. '、'C. '、'D. ' 开头），" +
                                            "correct_answer（正确选项的索引，从0开始的整数），" +
                                            "explanation（答案解析，字符串，说明正确选项的理由及错误选项的排除原因，语言简洁清晰，适合初中生理解）。" +
                                            "示例格式：" +
                                            "[{" +
                                            "\"title\": \"The History of Computers\"," +
                                            "\"content\": \"Computers have changed a lot over the years...\"," +
                                            "\"questions\": [" +
                                            "{" +
                                            "\"question\": \"When were the first computers built?\"," +
                                            "\"options\": [\"A. In the 1940s\", \"B. In the 1950s\", \"C. In the 1960s\", \"D. In the 1970s\"]," +
                                            "\"correct_answer\": 0," +
                                            "\"explanation\": \"The first electronic computers were built in the 1940s...\"" +
                                            "}" +
                                            "]" +
                                            "}]"
                            )));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );

        // 注意：这里需要替换为实际的大模型API地址
        Request request = new Request.Builder()
                .url("https://api.modelarts-maas.com/v1/chat/completions")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer xxx") // 如果需要认证
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: 网络请求失败");
                e.printStackTrace();
                if (readingPassagesCallback != null) {
                    readingPassagesCallback.onError("网络请求失败");
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d(TAG, "onResponse: 网络请求成功");
                    try {
                        String responseData = response.body().string();
                        Log.d(TAG, "onResponse: 响应数据：" + responseData);

                        // 解析响应数据
                        JSONObject responseJson = new JSONObject(responseData);
                        JSONArray choices = responseJson.getJSONArray("choices");
                        JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                        String content = message.getString("content");

                        parseReadingPassagesFromResponse(content);
                        
                        // 通知回调
                        if (readingPassagesCallback != null && readingPassages != null) {
                            readingPassagesCallback.onReadingPassagesLoaded(readingPassages);
                        }
                    } catch (Exception e) {
                        Log.d(TAG, "onResponse: 网络请求异常");
                        e.printStackTrace();
                        if (readingPassagesCallback != null) {
                            readingPassagesCallback.onError("解析数据失败");
                        }
                    }
                } else {
                    Log.d(TAG, "onResponse: fail");
                    if (readingPassagesCallback != null) {
                        readingPassagesCallback.onError("请求失败");
                    }
                }
            }
        });
    }

    public boolean isNetworkAvailable(Context ctx) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Network network = connectivityManager.getActiveNetwork();
                NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
                return capabilities != null &&
                        (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
            } else {
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                return activeNetworkInfo != null && activeNetworkInfo.isConnected();
            }
        }
        return false;
    }


    public void parseQuestionsFromResponse(String responseData) {
        questions = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject questionObj = jsonArray.getJSONObject(i);
                String question = questionObj.getString("question");
                JSONArray optionsArray = questionObj.getJSONArray("options");
                String[] options = new String[optionsArray.length()];
                for (int j = 0; j < optionsArray.length(); j++) {
                    options[j] = optionsArray.getString(j);
                }
                int correctAnswer = questionObj.getInt("correct_answer");
                String explanation = questionObj.getString("explanation");

                questions.add(new GrammarQuestion(question, options, correctAnswer, explanation));
            }
            Log.d(TAG, "parseQuestionsFromResponse: 题目解析成功，题目数：" + questions.size());
        } catch (JSONException e) {
            Log.d(TAG, "parseQuestionsFromResponse: 题目解析失败");
            e.printStackTrace();
        }
    }
    
    public void parseReadingPassagesFromResponse(String responseData) {
        readingPassages = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject passageObj = jsonArray.getJSONObject(i);
                String title = passageObj.getString("title");
                String content = passageObj.getString("content");
                
                JSONArray questionsArray = passageObj.getJSONArray("questions");
                ReadingQuestion[] questions = new ReadingQuestion[questionsArray.length()];
                for (int j = 0; j < questionsArray.length(); j++) {
                    JSONObject questionObj = questionsArray.getJSONObject(j);
                    String question = questionObj.getString("question");
                    JSONArray optionsArray = questionObj.getJSONArray("options");
                    String[] options = new String[optionsArray.length()];
                    for (int k = 0; k < optionsArray.length(); k++) {
                        options[k] = optionsArray.getString(k);
                    }
                    int correctAnswer = questionObj.getInt("correct_answer");
                    String explanation = questionObj.getString("explanation");

                    questions[j] = new ReadingQuestion(question, options, correctAnswer, explanation);
                }

                readingPassages.add(new ReadingPassage(title, content, questions));
            }
            Log.d(TAG, "parseReadingPassagesFromResponse: 阅读理解解析成功，文章数：" + readingPassages.size());
        } catch (JSONException e) {
            Log.d(TAG, "parseReadingPassagesFromResponse: 阅读理解解析失败");
            e.printStackTrace();
        }
    }
    
    // 获取题目列表
    public List<GrammarQuestion> getQuestions() {
        return questions;
    }
    
    // 获取阅读理解文章列表
    public List<ReadingPassage> getReadingPassages() {
        return readingPassages;
    }
    
    // 获取当前题目
    public GrammarQuestion getCurrentQuestion() {
        if (questions != null && !questions.isEmpty() && currentQuestionIndex < questions.size()) {
            return questions.get(currentQuestionIndex);
        }
        return null;
    }
    
    // 设置当前题目索引
    public void setCurrentQuestionIndex(int index) {
        if (questions != null && index >= 0 && index < questions.size()) {
            currentQuestionIndex = index;
        }
    }
}